//
//  KDRepostController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/6/24.
//  Copyright (c) 2015年 魏强. All rights reserved.
//  文字上报页

#import "KDReportController.h"
#import "KDReportParam.h"
#import "KDPatrolgetReportResult.h"
#import "KDPatrolPageRequestTool.h"
#import "SVProgressHUD.h"
#import "KDPullDownMenu.h"
#import "KDPullDownMenuModel.h"
#import "KDProvinceController.h"
#import "KDGetAllClueTyoeResult.h"
#import "KDClueType.h"
#import "AFNetworking.h"
#import "KDReginType.h"
#import "KDReportRequestTool.h"
#import "KDCompany.h"
#import "KDInfoType.h"
#import "KDCity.h"
#import "NSDictionary+WQExtension.h"
#import "KDReginPickerController.h"
#import "KDInfoTypeController.h"
#import "UIViewController+BackButtonHandler.h"
#import "KDTabBarController.h"
#import "KDPicsCell.h"
#import "ZZPhotoKit.h"
#import "LXActionSheet.h"
#import "NSString+KD.h"
#define CellH 40
#define MenuMIX_Height 65//下拉菜单的最低高度
@interface KDReportController ()<UIAlertViewDelegate, KDPullDownMenuDelegate, UITextFieldDelegate,UITextViewDelegate,KDReginPickerControllerDelegate,BackButtonHandlerProtocol,UICollectionViewDataSource,UICollectionViewDelegate,LXActionSheetDelegate>
/**
 *  标题
 */
@property (weak, nonatomic) IBOutlet UITextField *titleTf;
/**
 *  核查人textfield
 */
@property (weak, nonatomic) IBOutlet UITextField *recheckPeopleTf;
/**
 *  审核人textfield
 */
@property (weak, nonatomic) IBOutlet UITextField *approvePeopleTf;
/**
 *  信息时间tf
 */
@property (weak, nonatomic) IBOutlet UITextField *timeTf;
/**
 *  发帖网名tf
 */
//@property (weak, nonatomic) IBOutlet UITextField *posterNameTf;
/**
 *  网站名称tf
 */
@property (weak, nonatomic) IBOutlet UITextField *websiteNameTf;

/**
 *  其他描述tv
 */
//@property (weak, nonatomic) IBOutlet UITextView *describeTv;
/**
 *  其他描述tv的PlaceHolder
 */
//@property (weak, nonatomic) IBOutlet UILabel *describeTvPH;

/**
 *  上报内容tv
 */
@property (weak, nonatomic) IBOutlet UITextView *contentTv;
/**
 *  上报内容tv的PlaceHolder
 */
@property (weak, nonatomic) IBOutlet UILabel *contentTvPlaceHolder;

/**
 *  工作要求tv
 */
//@property (weak, nonatomic) IBOutlet UITextView *taskTv;
/**
 *  工作要求tv的PlaceHolder
 */
//@property (weak, nonatomic) IBOutlet UILabel *taskTvPH;
/**
 *  原始信息描述Tv
 */
//@property (weak, nonatomic) IBOutlet UITextView *originalContentTv;
/**
 *  原始信息描述Tv的PlaceHolder
 */
//@property (weak, nonatomic) IBOutlet UILabel *originalContentTvPH;

/**
 *  提交按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

/**
 *  控制器页面底部的scrollView
 */
@property (weak, nonatomic) IBOutlet UIScrollView *scrollVIew;
/**
 *  scrollView距离顶部的约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTop_Constraint;
/**
 *  第一大块下拉控件的底部
 */
@property (weak, nonatomic) IBOutlet UIView *pullUnderView;
/**
 *  第二块下拉控件的底部
 */
@property (weak, nonatomic) IBOutlet UIView *pullUnderView2;

/**
 *  整个scrollView的高
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *clearViewConstraint_H;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *clearViewConstraint_W;
/**
 *  兜住下拉控件的underView1，他的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pullUnderViewConstraint_height;
/**
 *  兜住下拉控件的underView2，他的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pullUnderView2Constraint_height;

/**
 *  装所有下拉控件的模型的数组
 */
@property (nonatomic, strong) NSArray *modelArr;
/**
 *  keyoard的高度
 */
@property (nonatomic, assign) CGFloat keyboardH;

@property (weak, nonatomic) IBOutlet UIButton *reginView;
/**
 *  线索模型的汇总
 */
@property (nonatomic, strong) NSArray *clues;


/**  所有可上报的接收单位 */
@property (nonatomic, strong) NSArray *Companys;

/**  所有的线索来源类型 */
@property (nonatomic, strong) NSArray *cueSources;

/**  所有可供选择的辖区 */
@property (nonatomic, strong) NSArray *citys;

/**  所有可供选择的信息类别 */
@property (nonatomic, strong) NSArray *infoTypes;

/**  当计数为2时，可以开始布置下拉菜单 */
@property (nonatomic, assign) NSInteger addUIClock;
@property (weak, nonatomic) IBOutlet UIButton *infotypeBtn;
/**  图片集成展示的collectionView  */
@property(strong,nonatomic) UICollectionView *collectionView;


/**  <#Description#> */
@property (nonatomic, strong) LXActionSheet *actionSheet;

@end

@implementation KDReportController
#pragma mark - 懒加载区
- (void)setAddUIClock:(NSInteger)addUIClock{
    _addUIClock = addUIClock;
    if (addUIClock == 2) {
        [self setUpPullDownMenuModel];
    }
}

- (NSArray *)picArray
{
    if (!_picArray) {
        UIImage *image = [UIImage imageNamed:@"添加照片"];
        _picArray = @[image] ;
    }
    return _picArray;
}
#pragma mark - 板块设置区
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.clearViewConstraint_W.constant = screenW;
    [self.view layoutIfNeeded];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setUpUnrequestMenuModel];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupCollectionView];
    self.contentTv.delegate = self;
    self.websiteNameTf.delegate = self;
    self.contentTv.returnKeyType = UIReturnKeyDone;
    self.timeTf.returnKeyType =UIReturnKeyDone;
    self.websiteNameTf.returnKeyType = UIReturnKeyDone;
    //传入title
    if (self.param.report_title) {
        self.titleTf.text = self.param.report_title;
    }
    
    //传入content
    if (self.param.report_content) {
//        self.contentTv.text = self.param.info_content;
        self.contentTv.attributedText = [NSString praseHtmlStr:self.param.report_content.stringByRemovingPercentEncoding];
        _contentTvPlaceHolder.text = @"";
    }
    self.titleTf.delegate = self;
    self.recheckPeopleTf.delegate = self;
    self.approvePeopleTf.delegate = self;
    self.navigationItem.title = @"上报";
    self.view.backgroundColor = BackGroundColor;
    self.submitBtn.backgroundColor = KDHeadColor;
    self.submitBtn.layer.cornerRadius = 3.0f;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ChooseInfoType:) name:@"ChooseInfoTypeToReportControllerNoty" object:nil];


}
/**
 *  设置必填项下拉框的model
 */
- (void)setUpPullDownMenuModel{
    
    KDPullDownMenuModel *typemodel = [[KDPullDownMenuModel alloc]init];
    NSMutableArray *names = [NSMutableArray array];
    NSMutableArray *IDs = [NSMutableArray array];
    int i = 0;
    for (KDClueType *model in self.clues) {
        [names addObject:model.cue_name];
        [IDs addObject:@(model.clueType_id)];
        if (self.type && self.param.source_type == model.clueType_id) {
            typemodel.titleName = model.cue_name;
            typemodel.index = i;
        }
        i++;
    }
    if (names.count != 0) {
        typemodel.allTypeArr = names;
        typemodel.allIdArr = IDs;
    }
    
    typemodel.typeName = @"线索来源";
    typemodel.required = YES;
    
    KDPullDownMenuModel *infoTypemodel = [[KDPullDownMenuModel alloc]init];
    infoTypemodel.allTypeArr = @[@"单条", @"综述", @"落深度研判"];
    infoTypemodel.typeName = @"报送类型";
    infoTypemodel.required = YES;
    infoTypemodel.allIdArr = @[@(1), @(2), @(3)];
    
    KDPullDownMenuModel *companyTypeModel = [[KDPullDownMenuModel alloc]init];
    NSMutableArray *names1 = [NSMutableArray array];
    NSMutableArray *IDs1 = [NSMutableArray array];
    i = 0;
    for (KDCompany *model1 in self.Companys) {
        [names1 addObject:model1.dept_name];
        [IDs1 addObject:@(model1.dept_id)];
        if (self.type && self.param.to_comp_id == model1.dept_id) {
            companyTypeModel.titleName = model1.dept_name;
            companyTypeModel.index = i;
        }
        i++;
    }
    if (names1.count != 0) {
        companyTypeModel.allTypeArr = names1;
        companyTypeModel.allIdArr = IDs1;
    }
    companyTypeModel.typeName = @"接收单位";
    companyTypeModel.required = YES;
    
    
    
    NSArray *arr = @[companyTypeModel, typemodel,infoTypemodel];
    if (self.type) {//说明是重新上报，
        int i = 0;
        for (NSNumber *ID in infoTypemodel.allIdArr) {
            if (ID.integerValue == self.param.report_type) {
                infoTypemodel.titleName = infoTypemodel.allTypeArr[i];
                infoTypemodel.index = i;
                break;
            }
            i++;
        }
    
    }else{
        self.param.source_type = [IDs[0] integerValue];
        self.param.to_comp_id = [IDs1[0] integerValue];
        self.param.report_type = [infoTypemodel.allIdArr[0] integerValue];
    }
    [self setUpPullDownMenuWithArray:arr andIsRequest:YES];
}
/**
 *  设置非必填项下拉框的model
 */
- (void)setUpUnrequestMenuModel{
    
    KDPullDownMenuModel *keywordmodel = [[KDPullDownMenuModel alloc]init];
    keywordmodel.allTypeArr = @[@"无",@"一级", @"二级", @"三级", @"四级", @"五级"];
    keywordmodel.typeName = @"紧急程度";
    keywordmodel.required = NO;
    keywordmodel.allIdArr = @[@(0), @(1), @(2), @(3), @(4),@(5)];
    NSArray *arr = @[keywordmodel];
    self.modelArr = arr;
    [self setUpPullDownMenuWithArray:arr andIsRequest:NO];
}
/**
 *  加载下拉列表控件
 *
 *  @param array     有几个下拉框
 *  @param isRequest 是不是必填项的
 */
- (void)setUpPullDownMenuWithArray:(NSArray *)array andIsRequest:(BOOL)isRequest{
    if (isRequest == YES) {//如果是必填项的那一堆，就加载pullUnderView1
        for (int i = 0; i < array.count; i++) {
            KDPullDownMenuModel *model = array[i];
            KDPullDownMenu *menu = [KDPullDownMenu pullDownMenuWithFrame:CGRectMake(0, i*(MenuMIX_Height ), self.pullUnderView.width, MenuMIX_Height)];
            menu.delegate = self;
            menu.model = model;
            [self.pullUnderView addSubview:menu];
        }
    }else{//如果不是必填项的那一堆，就加载pullUnderView2
        for (int i = 0; i < array.count; i++) {
            KDPullDownMenuModel *model = array[i];
            KDPullDownMenu *menu = [KDPullDownMenu pullDownMenuWithFrame:CGRectMake(0, i*(MenuMIX_Height ), self.pullUnderView.width, MenuMIX_Height)];
            menu.delegate = self;
            menu.model = model;
            [self.pullUnderView2 addSubview:menu];
        }
    }
}

- (void)setupCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat magin = 10.0;
    CGFloat photoSize = (screenW - 20*2 -magin*2) / 3;
    flowLayout.minimumInteritemSpacing = 10.0;//item 之间的行的距离
    flowLayout.minimumLineSpacing = magin;//item 之间竖的距离
    flowLayout.itemSize = (CGSize){photoSize,photoSize};
    //        self.sectionInset = UIEdgeInsetsMake(0, 2, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [self.scrollVIew addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.pullUnderView2.left);
        make.right.mas_equalTo(self.pullUnderView2.mas_right);
        make.top.mas_equalTo(self.pullUnderView2.mas_bottom).offset(10);
        make.height.equalTo(@(photoSize ));
    }];
    [_collectionView registerClass:[KDPicsCell class] forCellWithReuseIdentifier:@"KDPicsCell"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView setUserInteractionEnabled:YES];
    
}
#pragma mark - 事件点击区



/**
 *  提交报告被点击了
 */
- (IBAction)submitBtnClick:(UIButton *)sender {
    if (self.picArray.count>1) {
        UIImage *image ;
        if ([[self.picArray objectAtIndex:0] isKindOfClass:[ZZPhoto class]]) {
            
            //从数组里面把model取出来
            ZZPhoto *photo = [self.picArray objectAtIndex:0];
            image = photo.originImage;
        }else{
            ZZCamera *camera = [self.picArray objectAtIndex:0];
            image = camera.image;
        }
        [SVProgressHUD showWithStatus:@"上传图片中……" maskType:SVProgressHUDMaskTypeGradient];
        [self uploadWithImage:image AndFinish:^(NSDictionary *result, NSError *a) {
            [SVProgressHUD dismiss];
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:result];
            [dic setObject:@1 forKey:@"type"];
            KDLog(@"%@",dic);

            [KDReportRequestTool uploadPicInfoWithWithParam:dic success:^(KDBaseResult *responseObejct) {
                KDLog(@"%@",responseObejct.msg);
            } failure:^(NSError *error) {
                KDLog(@"%@",error);
            }];
        }];
    }
    
    KDAccount *account = [KDAccountTool account];
    
    self.param.editor = account.userName;
    self.param.editor_tel = account.phone;
    self.param.report_title = self.titleTf.text;
//    self.param.recheckPeople = self.recheckPeopleTf.text;
//    self.param.approvePeople = self.approvePeopleTf.text;
    self.param.report_content = self.contentTv.text;
//    self.param.st = self.timeTf.text;
//    self.param.ori_webname = self.websiteNameTf.text;
    NSArray *peoples = [self.websiteNameTf.text componentsSeparatedByString:@"，"];
    self.param.info_people = peoples;
    if (!self.param.website_name) {
        self.param.website_name = @" ";
    }
    KDReportParam *param = [[KDReportParam alloc]init];
    param = self.param;
    
//    self.param.ori_author = self.posterNameTf.text;
    //判断各种内容是否有填写
    if ( ![self checkMessage]) {
        return;
    } ;
    [SVProgressHUD showWithStatus:@"正在上报" maskType:SVProgressHUDMaskTypeGradient ];
    [KDReportRequestTool addReportInfoWithParam:[param keyValues] success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            [SVProgressHUD showSuccessWithStatus:@"上传成功" maskType:SVProgressHUDMaskTypeGradient];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
    
  
}
/**
 *  确认信息是否填写完整
 *
 *  @return 返回YES表示填写完整
 */
- (BOOL)checkMessage
{
//    if (self.param.ori_author.length == 0) {//如果
//        self.param.ori_author = nil;
//    }
    if (self.param.report_title.length == 0) {

        [SVProgressHUD showErrorWithStatus:@"请填写上报标题" maskType:SVProgressHUDMaskTypeGradient];
//        [av show];
        return NO;
    }else if (self.param.report_content.length == 0){

        [SVProgressHUD showErrorWithStatus:@"请填写报送内容" maskType:SVProgressHUDMaskTypeGradient];
        return NO;
    }
    
    if (!self.param.regionsArr.count) {

        [SVProgressHUD showErrorWithStatus:@"请进行辖区选择" maskType:SVProgressHUDMaskTypeGradient];

        return NO;
    }
    if (!self.param.about_type) {
        //        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写报送内容" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        //        [av show];
        [SVProgressHUD showErrorWithStatus:@"请进行信息类别选择" maskType:SVProgressHUDMaskTypeGradient];
        
        return NO;
    }
    
//    else if (self.param.com.length == 0){
//        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写信息时间" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [av show];
//        return NO;
//    }else if (self.param.ori_author.length == 0){
//        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写发帖网名" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [av show];
//        return NO;
//    }else if (self.param.ori_webname.length == 0){
//        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写网站名称" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [av show];
//        return NO;
//    }else if (self.param.recheckPeople.length == 0){
//        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写核查人" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [av show];
//        return NO;
//    }else if (self.param.approvePeople.length == 0){
//        UIAlertView *av = [[UIAlertView alloc]initWithTitle:nil message:@"请填写审核人" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//        [av show];
//        return NO;
//    }
    return YES;
}

- (IBAction)removeKeyboard:(id)sender {
    [self.view endEditing:YES];
}
/**
 *  辖区按钮被点击了
 */
- (IBAction)reginViewClick:(UIButton *)sender {
    KDReginPickerController *vc = [[KDReginPickerController alloc]init];
    vc.delegate = self;
    vc.citys = self.citys;
//    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];

}
/**
 *  信息类别被点击了
 */
- (IBAction)infoTypeBtnClick:(UIButton *)sender {
    KDInfoTypeController *info = [[KDInfoTypeController alloc]init];
    info.infoTypes = self.infoTypes;
    [self.navigationController pushViewController:info animated:YES];

}


#pragma mark - 网络请求区
- (void)loadData{
    //1.获取到网站类型
    WS(ws);
    __weak __typeof(self)weakSelf = self;
    [KDReportRequestTool getWebsitTypesWithParam:nil success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            NSDictionary *dic = [NSDictionary dictionaryWithJsonString:(NSString *)responseObejct.data];
            
            NSArray *arr = [dic allValues];
            
            self.param.website_type_name = arr[self.param.website_type];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
             [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
//        [SVProgressHUD showErrorWithStatus:@"" maskType:<#(SVProgressHUDMaskType)#>]
    }];
    
    
    //2.获取到可接收报告的单位
    [KDReportRequestTool getCompanysWithParam:nil success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.Companys = [KDCompany objectArrayWithKeyValuesArray:responseObejct.info];
            weakSelf.addUIClock++;
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [ws.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
//            [ws.currentTabV.header endRefreshing];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
    
    //3.获取所有线索
    [KDReportRequestTool getCueSourcesWithParam:nil success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            ws.clues = [KDClueType objectArrayWithKeyValuesArray:responseObejct.data];
            
            weakSelf.addUIClock++;
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [ws.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
    
    //4.获取所有城市
    [KDReportRequestTool getCitysWithParam:nil success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            ws.citys = [KDCity objectArrayWithKeyValuesArray:responseObejct.info];
            if (ws.type) {
                NSString *str = [NSString string];
                NSArray *regionsArr = [ws.param.regions JSONValue];
                for (NSNumber *num in regionsArr)
                {
                    if ([num isKindOfClass:[NSNumber class]]) {
                        for (KDCity *city in ws.citys)
                        {
                            if (city.city_id == num.integerValue)
                            {
                                str = [str stringByAppendingString:[NSString stringWithFormat:@"%@ ",city.city_name]];
                                break;
                            }
                        }
                    }
                   
                    
                }
                if (str.length) {
                    [ws.reginView setTitle:str forState:UIControlStateNormal];
                }
            }
           
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [ws.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
    
    //5.获取信息类别
    [KDReportRequestTool getInfoTypesWithParam:nil success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            ws.infoTypes = [KDInfoType objectArrayWithKeyValuesArray:responseObejct.info];
            if (ws.type) {
                for (KDInfoType *type in ws.infoTypes) {
                    if (type.ID == ws.param.about_type) {
                        [ws.infotypeBtn setTitle:type.info_type_name forState:UIControlStateNormal];
                        break;
                    }
                }
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
    
}

//上传图片(单张)
- (void)uploadWithImage:(UIImage*)image AndFinish:(void (^)(NSDictionary *, NSError *))finish
{
    
    //1. 存放图片的服务器地址，这里我用的宏定义
    NSString * url = @"http://monitor.szkedun.cn/fupload/submit";
    
    //2. 利用时间戳当做图片名字
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *imageName = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg",imageName];
    
    //3. 图片二进制文件
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
    KDLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
    
    //4. 发起网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 上传图片，以文件流的格式，这里注意：name是指服务器端的文件夹名字
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //上传成功时的回调
        KDLog(@"%@",responseObject);
        finish(responseObject,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败时的回调
        finish(nil,error);
    }];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
                break;
            default:
                break;}
    }else{
        switch (buttonIndex) {
            case 0:
                [self.navigationController popViewControllerAnimated:YES];
                break;
            default:
                break;
        }
    }
}
/**
 *  下拉菜单的delegate
 *
 *  @return 返回一个是在下拉还是在上拉
 */
#pragma  mark - KDPullDownMenuDelegate
- (void)KDPullDownMenu:(KDPullDownMenu *)menu PullDownOrPullUp:(BOOL)pull
{
    //下拉或者上拉的高度
    CGFloat height;
    if (menu.model.allTypeArr.count < 5) {
        height = menu.model.allTypeArr.count * CellH;
    }else{
        height = 5 * CellH;
    }
    if (menu.model.isRequired == YES) {//是必填项，也就是第一个下拉块
        if (pull) {//如果是下拉
            for (KDPullDownMenu *mu in self.pullUnderView.subviews) {//将底下的其他下拉菜单一起向下移动
                if (menu.y < mu.y) {
                    mu.y = mu.y + height;
                }
            }
            //调整整个scrollView的contensize
            self.scrollVIew.contentSize = CGSizeMake(self.scrollVIew.contentSize.width, self.scrollVIew.contentSize.height + height);
        }else{//如果是上拉
            for (KDPullDownMenu *mu in self.pullUnderView.subviews) {
                if (menu.y < mu.y) {
                    mu.y = mu.y - height;
                }}
            self.scrollVIew.contentSize = CGSizeMake(self.scrollVIew.contentSize.width, self.scrollVIew.contentSize.height - height);
            [self setValueWithModel:menu.model];
        }
        [UIView animateWithDuration:0.2f animations:^{
            self.pullUnderViewConstraint_height.constant = (pull) ? self.pullUnderViewConstraint_height.constant + height :self.pullUnderViewConstraint_height.constant - height;
            [self.view layoutIfNeeded];
        }];
    }else{//不是必填项，就是第二块下拉块
        if (pull) {//如果是下拉
            for (KDPullDownMenu *mu in self.pullUnderView2.subviews) {//将底下的其他下拉菜单一起向下移动
                if (menu.y < mu.y) {
                    mu.y = mu.y + height;
                }
            }
            //调整整个scrollView的contensize
            self.scrollVIew.contentSize = CGSizeMake(self.scrollVIew.contentSize.width, self.scrollVIew.contentSize.height + height);
        }else{//如果是上拉
            for (KDPullDownMenu *mu in self.pullUnderView2.subviews) {//找到比被选中的那行还要下的其他行
                if (menu.y < mu.y) {
                    mu.y = mu.y - height;
                }}
            self.scrollVIew.contentSize = CGSizeMake(self.scrollVIew.contentSize.width, self.scrollVIew.contentSize.height - height);
            //给param传值
            [self setValueWithModel:menu.model];
        }
        [UIView animateWithDuration:0.2f animations:^{
            self.pullUnderView2Constraint_height.constant = (pull) ? self.pullUnderView2Constraint_height.constant + height :self.pullUnderView2Constraint_height.constant - height;
            [self.view layoutIfNeeded];
        }];
    }
    
}

- (void)setValueWithModel:(KDPullDownMenuModel *)model{

    if (model.isRequired == YES) {//如果是必填项
       if ([model.typeName isEqualToString:@"线索来源"]){
            self.param.source_type = [model.allIdArr[model.index] intValue];
        }else if ([model.typeName isEqualToString:@"报送类型"]){
            self.param.report_type = [model.allIdArr[model.index] intValue];
        }else if ([model.typeName isEqualToString:@"接收单位"]){
            self.param.to_comp_id = [model.allIdArr[model.index] intValue];
        }
    }else{
        if ([model.typeName isEqualToString:@"紧急程度"]) {
            self.param.w_type = [model.allIdArr[model.index] intValue];
        }
    }
    
}

#pragma mark - UITextFieldDelegate
/**
 *  当textfield开始输入的时候会调用这个方法
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.superview.y > screenH * 0.7) {//如果那个textfield的高度在比较下面的话，就让整个View随着键盘的弹出也跟着往上弹。
        [UIView animateWithDuration:0.25 animations:^{
            self.view.y = -self.keyboardH + 64;
            [self.view layoutIfNeeded];
        }];
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma  mark - UITextViewDelegate
/**
 *  点击return就去掉键盘
 */
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
    if (textView == self.contentTv) {
        if (textView.text.length == 0) {
            _contentTvPlaceHolder.text = @"输入内容";
        }else{
            _contentTvPlaceHolder.text = @"";
        }
    }
//    else if (textView == self.taskTv){
//        if (textView.text.length == 0) {
//            _taskTvPH.text = @"输入内容";
//        }else{
//            _taskTvPH.text = @"";
//        }
//    }else if (textView == self.describeTv){
//        if (textView.text.length == 0) {
//            _describeTvPH.text = @"输入内容";
//        }else{
//            _describeTvPH.text = @"";
//        }
//    }else if (textView == self.originalContentTv){
//        if (textView.text.length == 0) {
//            _originalContentTvPH.text = @"输入内容";
//        }else{
//            _originalContentTvPH.text = @"";
//        }
//    }
   
}
#pragma mark - 通知

/**
 *  接收到返回的地址信息
 */
- (void)getAddress:(NSNotification *)noty{
    NSString *text = noty.userInfo[@"address"];
//    KDReginType *model = noty.userInfo[@"regionModel"];
//    self.model.m_Region =model.ID;
//    self.param.area = model.ID;
    [self.reginView setTitle: text forState:UIControlStateNormal];
}
/**
 *  接收到返回的信息类别通知
 *
 *  @param noty <#noty description#>
 */
- (void)ChooseInfoType:(NSNotification *)noty{
    NSString *text = noty.userInfo[@"infoName"];
    KDInfoType *model =noty.userInfo[@"infoType"];
    self.param.about_type = model.ID;
    [self.infotypeBtn setTitle:text forState:UIControlStateNormal];

}
#pragma mark - 弹出的对话框内容
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = nil;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark - KDReginPickerControllerDelegate
- (void)reginPickerControllerPopWithCitys:(NSArray *)citys{
    self.citys = citys;
    NSString *str = [NSString string];
    NSMutableArray *arr = [NSMutableArray array];
    for (KDCity *city in citys) {
        if (city.isCheck) {
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@ ",city.city_name]];
            [arr addObject:@(city.city_id)];
        }
    }
    self.param.regionsArr = arr;
//    self.param.regions = [arr JSONString];
    if (str.length) {
        [self.reginView setTitle:str forState:UIControlStateNormal];
    }else{
        [self.reginView setTitle:@"请点击进行辖区选择" forState:UIControlStateNormal];
    }
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    KDLog(@"%lu", (unsigned long)self.picArray.count);
    
    return self.picArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KDPicsCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KDPicsCell" forIndexPath:indexPath];
    if (!photoCell) {
        photoCell = [[KDPicsCell alloc]init];
    }
    if ([[self.picArray objectAtIndex:indexPath.row] isKindOfClass:[ZZPhoto class]]) {
        
        //从数组里面把model取出来
        ZZPhoto *photo = [self.picArray objectAtIndex:indexPath.row];
        
        //用photo对象中的originImage属性来展示图片
        photoCell.photo.image = photo.originImage;
        
        
    }else if([[self.picArray objectAtIndex:indexPath.row] isKindOfClass:[ZZCamera class]]){
        
        ZZCamera *camera = [self.picArray objectAtIndex:indexPath.row];
        photoCell.photo.image = camera.image;
        
    }else if ([[self.picArray objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]){
        photoCell.photo.image = self.picArray[indexPath.row];
    }
    
    
    return photoCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //先判断是不是有了
    if (self.picArray.count >=2) {
        [SVProgressHUD showInfoWithStatus:@"最多只可添加一张" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    if (indexPath.row == self.picArray.count-1) {//最后一个才是加图片
           LXActionSheet *actionSheet = [[LXActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拍照",@"从手机相册选择"]];
            
//            cameraBtn.enabled = !cameraBtn.enabled;

//        }
        UIWindow *window = [UIApplication sharedApplication].keyWindow;

        [actionSheet showInView:window];

    }else{//其他的都是删除
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.picArray];
        [arr removeObjectAtIndex:indexPath.row];
        self.picArray = arr;
        //    [self.picArray ];
        [_collectionView reloadData];
    }
    
}

#pragma mark - BackButtonHandlerProtocol
- (BOOL)navigationShouldPopOnBackButton{
    if (_delegate &&[_delegate respondsToSelector:@selector(reportCtrlPopBySuccessReportWithIndex:)]) {
        [_delegate reportCtrlPopBySuccessReportWithIndex:_cellIndex];
    }
    
    return YES;
}

#pragma mark - LXActionSheetDelegate代理

- (void)didClickOnButtonIndex:(NSInteger *)buttonIndex{
    int btnIndex = (int)buttonIndex;
    if (!btnIndex) {
        
        ZZCameraController *cameraController = [[ZZCameraController alloc]init];
        cameraController.takePhotoOfMax = 1;
        
        cameraController.isSaveLocal = NO;
        [cameraController showIn:self result:^(id responseObject){
            
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.picArray];
            NSArray *photos = (NSArray *)responseObject;
            [arr insertObjects:photos atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, photos.count)]];
            
            self.picArray = arr;
            
            
            [_collectionView reloadData];
        }];
    }else if (btnIndex == 1){
        //点中了倒数第一个，就让他去相册找
        
        ZZPhotoController *photoController = [[ZZPhotoController alloc]init];
        photoController.selectPhotoOfMax = 1;
        //设置相册中完成按钮旁边小圆点颜色。
        //        photoController.roundColor = [UIColor greenColor];
        
        [photoController showIn:self result:^(id responseObject){
            NSMutableArray *arr = [NSMutableArray arrayWithArray:self.picArray];
            NSArray *photos = (NSArray *)responseObject;
            [arr insertObjects:photos atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, photos.count)]];
            self.picArray = arr;
//                        KDLog(@"重载");
            [_collectionView reloadData];
            
        }];
    }
}

@end
